package com.cwt_taxi_xa;

import android.app.ProgressDialog;
import android.app.Service;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.protocol.can.IViewAirConditionState;
import com.cwt_taxi_xa.protocol.mcu.IViewFmManager;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.Tools;

import java.util.ArrayList;

public class ActivityFM extends CWTBaseActivity implements IViewFmManager {

	final static String TAG = "ActivityFM";
	public static boolean isview = false;
	
	ImageView iv_soutai, iv_shoucangjia, iv_bofang, iv_shangyishou, iv_xiayishou, iv_shoucang;
	LinearLayout ly_rongqi;
	LinearLayout ly_shoucang;
	boolean scview = false;
	LinearLayout ly_fanhui, ly_shoucangclick;
	
	SeekBar sb,sbFrequency;
	TextView tv;
	
	
	String sp_list = "FMlist";
	String sp_list_sc = "FMlist_sc";

	static String[] pls;//上次搜索-指令数据
	static String[] plints;//上次搜索-显示数据

	static String[] scs;//收藏
	static String[] scints;
	
	ProgressDialog pd;
	
	static boolean now_playing = false;
	static boolean redHeart = false;

	public static boolean soutai = false;//用于应付mcu 一直发搜台结果上来的bug

	// 状态栏的时间和状态标志
	TextView tv_time;
	ImageView iv_online, iv_center, iv_gps,ivFuelError;


	ListView lv_sc;
	ArrayAdapter<String> adapter_sc;

	//启用焦点功能
	private boolean useAudioFocus = true;
	private int status = AudioManager.AUDIOFOCUS_REQUEST_FAILED;
	private AudioManager mAudioManager;

	Animation mAlphaAnim ;
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1001){
				if(pd!=null)pd.dismiss();
				pls = (String[]) msg.obj;
				
				refreshPls();
				
				shouTai(nowclick);
				//shouTai(nowclick);
				
				
				if(pls.length>0){
					SPUtils.setParam(sp_list, list2str(pls));
				}
				
			}else if (msg.what == 1002) {
				AppLog.d(TAG,"--------------- 请开始搜台");
				readyStart();
			}else if (msg.what == 1003) {
					tv_time.setText((String) msg.obj);
			}else if (msg.what == 1007) {
				// 刷新右上角状态位-网络
				iv_online
						.setImageResource((Boolean) msg.obj ? R.drawable.cwtic_bs1_on
								: R.drawable.cwtic_bs1_off);
			} else if (msg.what == 1008) {
				// 刷新右上角状态位-平台
				iv_center
						.setImageResource((Boolean) msg.obj ? R.drawable.cwtic_bs2_on
								: R.drawable.cwtic_bs2_off);
			} else if (msg.what == 1009) {
				// 刷新右上角状态位-定位
				iv_gps
						.setImageResource((Boolean) msg.obj ? R.drawable.cwtic_bs3_on
								: R.drawable.cwtic_bs3_off);
			}
		};
	};



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fm2);
		AppLog.d(TAG,"onCreate");
		//打开fm
		MCUUtil.openFM();
		if(useAudioFocus){
			requestAudioFocus();
		}
		mAlphaAnim = AnimationUtils.loadAnimation(this, R.anim.alpha_anim);
		iv_bofang = (ImageView) findViewById(R.id.imageView2);
		iv_shangyishou = (ImageView) findViewById(R.id.imageView5);
		iv_xiayishou = (ImageView) findViewById(R.id.imageView6);
		iv_soutai = (ImageView) findViewById(R.id.imageView4);
		iv_shoucangjia = (ImageView) findViewById(R.id.imageView3);
		iv_shoucang = (ImageView) findViewById(R.id.imageView88);
		ly_rongqi = (LinearLayout) findViewById(R.id.ly_rongqi);
		ly_shoucang = (LinearLayout) findViewById(R.id.ly_shoucang);
		ly_fanhui = (LinearLayout) findViewById(R.id.ly_click_fanhui);
		ly_shoucangclick = (LinearLayout) findViewById(R.id.ly_click_shoucang);
		sb = (SeekBar) findViewById(R.id.seekBar1);
		sbFrequency = (SeekBar) findViewById(R.id.sb_frequency);
		tv = (TextView) findViewById(R.id.textView2);
		lv_sc = (ListView) findViewById(R.id.listView1);
		ivFuelError = (ImageView) findViewById(R.id.iv_fuel_error);
		MCUUtil.mConditioningDecode.registerState(conditionState);
		sbFrequency.setMax(205);
		sbFrequency.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				if(fromUser){
					int value = 87500 + seekBar.getProgress() * 100;
					try {
						String ddd = Tools.parseByte2HexStr(Tools.int2Bytes2(value,4));
						AppLog.d(TAG,"sbFrequency:" + ddd);
						setFM(ddd);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});
		lv_sc.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				setFM(scs[arg2]);
				if(nowclick>-1){
					pltvs[nowclick].setBackgroundResource(R.drawable.selectoff);
					nowclick = -1;
				}
				nowclick_sc = arg2;
				setSeleview(scints[arg2]);
			}
		});
		
		tv_time = (TextView) findViewById(R.id.textView1);

		iv_online = (ImageView) findViewById(R.id.imageView8);
		iv_center = (ImageView) findViewById(R.id.imageView9);
		iv_gps = (ImageView) findViewById(R.id.imageView10);
		
		sb.setMax(25);
		sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
			}
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
			}
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				MCUUtil.setvol(arg1, "FM界面音量控件变动");
			}
		});
		
		iv_bofang.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(now_playing){
					MCUUtil.selecterVic(2);
					now_playing = false;
					iv_bofang.setImageResource(R.drawable.bofang);
				}else{
					if(tv.getText().toString().equals("--.--")){
						Toast.makeText(ActivityFM.this, "请选台", 1000).show();
					}else{
						MCUUtil.selecterVic(1);
						String nowpl = SPUtils.getParamString("fmnowpl", "");
						if(!nowpl.equals("")){
							setFM(nowpl);
						}
						now_playing = true;
						iv_bofang.setImageResource(R.drawable.zanting);
					}
				}
			}
		});
		
		
		ly_shoucangclick.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				String s1 = list2str(scs);
				String nowpl = null;
				
				
				if(tv.getText().toString().equals("--.--")){
					Toast.makeText(ActivityFM.this, "请选台", 1000).show();
				}else{
					nowpl = SPUtils.getParamString("fmnowpl", "");
					if(nowpl.equals("")){
						return;
					}
				}
				
				if(redHeart){
					redHeart = false;
					s1 = s1.replace(nowpl, "");
					iv_shoucang.setImageResource(R.drawable.heartoff);
				}else{
					redHeart = true;
					s1+=("-"+nowpl);
					iv_shoucang.setImageResource(R.drawable.hearton);
				}
				s1 = checkStr(s1);
				if(s1.equals("")){
					scs = new String[0];
				}else{
					scs = s1.split("-");
				}
				refreshScs();
				adapter_sc = new ArrayAdapter<>(ActivityFM.this, R.layout.adapter_fm, scints);
				lv_sc.setAdapter(adapter_sc);
			}
		});
		
		
		ly_fanhui.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//不想处理关闭收音机状态
				isview = false;
				MCUUtil.selecterVic(2);
				MCUUtil.closeFM();
				now_playing = false;
				finish();
				MCUUtil.mPartyControl.unregister(ActivityFM.this);
				MCUUtil.mCarRadio.setReady(false);
				if(useAudioFocus){
					abandonAudioFocus();
				}
			}
		});
	
		iv_soutai.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if (pd == null) {
					pd = ProgressDialog.show(ActivityFM.this, "请稍等", "正在搜台。。。");
				} else {
					pd.show();
				}
				startSearch();

			}
		});
		
		
		iv_shoucangjia.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(scview){
					scview = false;
					ly_shoucang.setVisibility(View.GONE);
				}else{
					scview = true;
					ly_shoucang.setVisibility(View.VISIBLE);
				}
			}
		});
		
		iv_shangyishou.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(nowclick>0){
					pltvs[nowclick-1].callOnClick();
				}else{
					pltvs[pltvs.length-1].callOnClick();
				}
			}
		});
		
		iv_xiayishou.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				try {
					if(nowclick<pltvs.length-1){
						pltvs[nowclick+1].callOnClick();
					}else{
						pltvs[0].callOnClick();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		//存放到onResume()时,没有方控按键会报错;
		MCUUtil.mPartyControl.register(this);
	}

    AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
			status = focusChange;
			AppLog.d(TAG,"onAudioFocusChange focusChange:" + focusChange);
            switch (focusChange){
                case AudioManager.AUDIOFOCUS_GAIN:
					AppLog.d(TAG,"onAudioFocusChange openFM:AUDIOFOCUS_GAIN");
                    //MCUUtil.openFM();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
					AppLog.d(TAG,"onAudioFocusChange closeFM:AUDIOFOCUS_LOSS");
					//MCUUtil.closeFM();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
					AppLog.d(TAG,"onAudioFocusChange closeFM:AUDIOFOCUS_LOSS_TRANSIENT");
					//MCUUtil.closeFM();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    break;
            }
        }
    };

    private void requestAudioFocus() {
        mAudioManager = (AudioManager)getSystemService(Service.AUDIO_SERVICE);
        status = mAudioManager.requestAudioFocus(audioFocusChangeListener,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
		AppLog.d(TAG,"requestAudioFocus status:" + status);
        if(status == AudioManager.AUDIOFOCUS_GAIN){

        }else{

        }
    }

    private void abandonAudioFocus(){
        mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    }

    protected String checkStr(String str) {
		// TODO Auto-generated method stub
		str = str.replace("--", "-");
		if(str.startsWith("-")){
			str = str.substring(1);
		}
		if(str.endsWith("-")){
			str = str.substring(0, str.length()-1);
		}
		return str;
	}
	
	protected void refreshPls() {
		// TODO Auto-generated method stub
		ArrayList<String> aypl = new ArrayList<>();
		ArrayList<String> ayplint = new ArrayList<>();
		
		try {
			for (int i = 0; i < pls.length-1; i++) {
				for (int j = i; j < pls.length; j++) {
					if(Integer.parseInt(pls[i], 16)>Integer.parseInt(pls[j], 16)){
						String str = pls[i];
						pls[i] = pls[j];
						pls[j] = str;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		for (int i = 0; i < pls.length; i++) {
			try {
				double pl = Integer.parseInt(pls[i], 16);
				pl = pl/1000;
				String nowpl = ""+pl;
				if(nowpl.length()<6){
					aypl.add(pls[i]);
					ayplint.add(nowpl);
				}
			} catch (Exception e) {
			}
		}
		
		plints = ayplint.toArray(new String[ayplint.size()]);
		pls = aypl.toArray(new String[aypl.size()]);
	}
	
	protected void refreshScs() {
		// TODO Auto-generated method stub
		if(scs!=null){
			scints = new String[scs.length];
			for (int i = 0; i < scints.length; i++) {
				double pl = Integer.parseInt(scs[i], 16);
				pl = pl/1000;
				scints[i] = ""+pl;
			}
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		AppLog.d(TAG,"onResume");
		isview = true;
		int vol = SPUtils.getParamInteger(SPConstants.SPK_vol, SPConstants.SPV_vol);
		AppLog.e("onResume当前获取声音："+vol + " status:" + status);
		//不要放onCreate()中,防止sendMsg收不到数据
		if(status != AudioManager.AUDIOFOCUS_GAIN && useAudioFocus){
			MCUUtil.openFM();
			abandonAudioFocus();
			requestAudioFocus();
		}
		if(TTsFunction.ttsvic){
			vol = TTsFunction.lastvic;
			AppLog.e("ttsing获取上次声音："+vol);
		}
		sb.setProgress(vol);
		String list = SPUtils.getParamString(sp_list, "");
		if(list.equals("")){
			if(MCUUtil.mCarRadio.isReady()){
				//readyStart();
			}
		}else{
			String[] result = list.split("-");
			handler.sendMessage(handler.obtainMessage(1001, result));
			now_playing = true;//二次进入都会暂停状态,修正
			//这里设置会有爆破音
			//MCUUtil.selecterVic(1);
		}
		iv_bofang.setImageResource(now_playing? R.drawable.zanting: R.drawable.bofang);
		iv_shoucang.setImageResource(redHeart? R.drawable.hearton: R.drawable.heartoff);
		

		//收藏
		String list_sc = SPUtils.getParamString(sp_list_sc, "");
		if(!list_sc.equals("")){
			scs = list_sc.split("-");
		}
		refreshScs();
		if(scints!=null){
			adapter_sc = new ArrayAdapter<>(ActivityFM.this, R.layout.adapter_fm, scints);
			lv_sc.setAdapter(adapter_sc);
		}
		
		tv.setText(showPLText);
		if(!SPUtils.getParamString("fmshowtext", "").equals("")){
			tv.setText(SPUtils.getParamString("fmshowtext", ""));
		}
		
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		isview = false;
		
		SPUtils.setParam(sp_list_sc, list2str(scs));
		showPLText = tv.getText().toString();
		SPUtils.setParam("fmshowtext", showPLText);
	}
	
	public synchronized void readyStart(){
		String list = SPUtils.getParamString(sp_list, "");
		AppLog.d(TAG,"readyStart list:" + list);
		if(list.equals("")){
			if(pd==null){
				pd = ProgressDialog.show(ActivityFM.this, "请稍等",
						"正在搜台。。。");
			}else{
				pd.show();
			}
			handler.post(new Runnable() {
				@Override
				public void run() {
					AppLog.d(TAG,"------------------ handler.postDelayed");
					startSearch();
				}
			});
			soutai = true;
		}
	}

	private synchronized void startSearch(){
		AppLog.d(TAG,"------------------ startSearch");
		SerialPortService.getInstance().sendSerialData7(MCUUtil.getMCUData(Tools.
				parseHexStr2Byte("55 35  000C 01 01 000155CC  0001A5E0")));
		MCUUtil.hasVic(false);
		soutai = true;
		searchTimeout();
	}

	private void searchTimeout(){
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				soutai = false;
				//结束静音
				MCUUtil.hasVic(true);
			}
		},30000);
	}

	String list2str(String[] list){
		String list_str = "";
		if(list!=null&&list.length>0){
			for (int i = 0; i < list.length; i++) {
				list_str+=(list[i]+"-");
			}
			list_str = list_str.substring(0, list_str.length()-1);
		}
		return list_str;
	}
	
	void setSeleview(String showtext){
		if(pltvs!=null){
			for (int i = 0; i < pltvs.length; i++) {
				if(pltvs[i].getText().toString().equals(showtext)){
					pltvs[i].setBackgroundResource(R.drawable.selecton);
					nowclick = i;
				}
			}
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==114||keyCode==133){
			int vol = SPUtils.getParamInteger(SPConstants.SPK_vol, SPConstants.SPV_vol);
			AppLog.e("onKeyDown当前获取声音："+vol + " keyCode:"  + keyCode);
			if(TTsFunction.ttsvic){
				vol = TTsFunction.lastvic;
				AppLog.e("ttsing获取上次声音："+vol);
			}
			sb.setProgress(vol);
		}
		return true;
	};
	
	static TextView[] pltvs;
	static int nowclick = -1;
	static int nowclick_sc = -1;
	void shouTai(int index){
		pltvs = new TextView[plints.length];
		ly_rongqi.removeAllViews();
		for (int i = 0; i < plints.length; i++) {
			pltvs[i] = new TextView(ActivityFM.this);
			pltvs[i].setText(plints[i]);
			if(index==i){
				pltvs[i].setBackgroundResource(R.drawable.selecton);
			}else{
				pltvs[i].setBackgroundResource(R.drawable.selectoff);
			}
			pltvs[i].setTag(i);
			pltvs[i].setTextColor(Color.parseColor("#ffffff"));
			pltvs[i].setTextSize(20);
			pltvs[i].setGravity(Gravity.CENTER);
			pltvs[i].setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if(nowclick>-1){
						pltvs[nowclick].setBackgroundResource(R.drawable.selectoff);
					}
					nowclick = (int) arg0.getTag();
					setFM(pls[nowclick]);
					setProgress(pls[nowclick]);
					pltvs[nowclick].setBackgroundResource(R.drawable.selecton);
				}
			});
			ly_rongqi.addView(pltvs[i]);
		}
	}

	static String showPLText = "--.--";
	void setFM(final String pl){
		//0x7a 0x33 00 06 0x00,0x01,0x86,0x0a xor 0x7a
		
		AppLog.d(TAG,"setFM pl:" + pl);
		if(MyStatus.vichl!=1){
			MCUUtil.selecterVic(1);
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				SerialPortService.getInstance().sendSerialData7(MCUUtil.getMCUData(Tools.
						parseHexStr2Byte("55 33 0006"+ pl)));
			}
		}).start();

		iv_bofang.setImageResource(R.drawable.zanting);
		
		now_playing = true;
		
		double db = Integer.parseInt(pl, 16);
		db = db/1000;
		tv.setText(""+db);
		SPUtils.setParam("fmnowpl", pl);
		
		iv_shoucang.setImageResource(R.drawable.heartoff);
		redHeart = false;
		if(scs!=null){
			for (int i = 0; i < scs.length; i++) {
				if(scs[i].equals(pl)){
					iv_shoucang.setImageResource(R.drawable.hearton);
					redHeart = true;
				}
			}
		}
	}
	
	void setProgress(String frequency){
		//Tools.parseHexStr2Byte(frequency);
		try {
			int value = bigBytes2Int(Tools.parseHexStr2Byte(frequency));
			AppLog.d(TAG, "setProgress frequency:" + frequency + " value:" + value);
			value = (value - 87500)/100;
			AppLog.d(TAG, "setProgress frequency:" + frequency + " value:" + value);
			sbFrequency.setProgress(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 大端模式
	 * 低地址存放高位字节
	 */
	public int bigBytes2Int(byte[] bytes) {
		int num = bytes[3] & 0xFF;
		num |= ((bytes[2] << 8) & 0xFF00);
		num |= ((bytes[1] << 16) & 0xFF0000);
		num |= ((bytes[0] << 24) & 0xFF000000);
		return num;
	}
	@Override
	public void setStatus(int index, boolean status) {
		switch (index) {
		case 1:
			handler.sendMessage(handler.obtainMessage(1007, status));
			break;
		case 2:
			handler.sendMessage(handler.obtainMessage(1008, status));
			break;
		case 3:
			handler.sendMessage(handler.obtainMessage(1009, status));
			break;
		default:
			break;
		}
	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub
		AppLog.d(TAG,"sendMsg type:" + type);
		//搜索完成
		if(type==789){
			if(soutai){
				endSearch(obj);
			}
		}else if(type==790){
			AppLog.d(TAG,"sendMsg 1002");
			if(isview){
				handler.sendMessage(handler.obtainMessage(1002, obj));
			}
		}else if (type == 1002) {
			//更新时间
			handler.sendMessage(handler.obtainMessage(1003, obj));
		}
	}

	@Override
	public void init(String text) {
		if(!TextUtils.isEmpty(text) ){
			if("功放初始化成功".equals(text)){
				MCUUtil.selecterVic(1);
			}
		}
	}

	private synchronized void endSearch(Object obj){
		soutai = false;
		handler.sendMessage(handler.obtainMessage(1001, obj));
		//结束静音
		MCUUtil.hasVic(true);
	}

	@Override
	public void setVolAdd() {
		onKeyDown(133,null);
	}

	@Override
	public void setVolLess() {
		onKeyDown(114,null);
	}

	@Override
	public void previous() {

		if(iv_shangyishou != null){
			try {
				iv_shangyishou.callOnClick();
			}catch (Exception e){
				e.printStackTrace();
			}
		}

	}

	@Override
	public void next() {
		if(iv_xiayishou != null){
			try {
				iv_xiayishou.callOnClick();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	IViewAirConditionState conditionState = new IViewAirConditionState(){

		@Override
		public void power(int type) {

		}

		@Override
		public void fuelAlarm(int alarm) {
			if(alarm == 1){
				ivFuelError.setVisibility(View.VISIBLE);
			}else{
				ivFuelError.setVisibility(View.INVISIBLE);//有时隐藏不了
			}
		}

		@Override
		public void heaterType(int heaterType) {
			//空调加热模式标志位

		}

		@Override
		public void heatingMode(int heatingMode) {
			//当前模式
		}
	};
}
